package com.qishon.pc.domain.util;

import com.qishon.pc.domain.model.ProgressControl;
import com.qishon.pc.domain.model.ProgressSteps;
import com.qishon.pc.domain.service.ProgressStepsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Created by yuquan.hu on 2017/1/5.
 */
@Slf4j
@Component
public class RenderUtil{

    @Autowired
    ProgressStepsService progressStepsSerivce;
    /**
     * 生成.mel文件
     * @param progressControl
     * @param filePath 渲染目录
     * @param scriptFile .mel文件生成目录
     * @throws Exception
     */
    public void writeScriptFile(String filePath,String scriptFile,ProgressControl progressControl,String mayaFile) throws  Exception {
        String mbFileName = "";//获取mb文件名
        String csv01FileName = "";//获取款号_01.csv
        String mbFilePath = filePath+"\\01.Model"+"\\"+progressControl.getGirard();
        File mbFile = new File(mbFilePath);
        File[] mbFiles = mbFile.listFiles();
        for(int i = 0;i < mbFiles.length;i++){
            if(mbFiles[i].getName().indexOf(progressControl.getGirard()+".mb") != -1){
                mbFileName = mbFiles[i].getName();
            }
            if (mbFiles[i].getName().indexOf("_01.csv") != -1){
                csv01FileName = mbFiles[i].getName();
            }
        }
        File _file = new File(scriptFile);
        if (!_file.exists()){
            _file.mkdirs();
        }
        File file = new File(scriptFile+"\\"+"userSetup.mel");
        if (file.exists()){
            file.delete();
            file.createNewFile();
        }else {
            file.createNewFile();
        }
        String _mbFile = "";
//        String _mbFile = mbFilePath+"\\"+"scenes"+"\\"+progressControl.getGirard()+".mb";
        File isMbFile = new File(mbFilePath+"\\"+"scenes");
        if (!isMbFile.exists()){
            //放弃当前渲染场景
            this.updateSteps(progressControl);
        }else {
            File[] scenesList = isMbFile.listFiles();
            boolean existence = false;
            if (scenesList != null){
                for (int i =0;i < scenesList.length;i++){
                    if (scenesList[i].getName().indexOf(".mb") >0){
                        _mbFile = scenesList[i].getPath();
                        existence = true;
                        break;
                    }
                }
            }else {
                //放弃当前渲染场景
                this.updateSteps(progressControl);
            }
            if (existence){
                _mbFile = _mbFile.replace("\\","/");
                String _csvFile = mbFilePath+"\\"+csv01FileName;
                _csvFile = _csvFile.replace("\\","/");
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(("source \"DeadlineMayaClient.mel\";\r\n").getBytes());
                fileOutputStream.write(("file -f -options \"v=0;\"  -esn false  -ignoreVersion " +
                        " -typ \"mayaBinary\" -o \""+_mbFile+"\";\r\n").getBytes());
                fileOutputStream.write(("addRecentFile(\""+_mbFile+"\", \"mayaBinary\");\r\n").getBytes());
                fileOutputStream.write(("global proc tjhUI()\r\n").getBytes());
                fileOutputStream.write(("{\r\n").getBytes());
                fileOutputStream.write(("     python \"callUI('"+_csvFile+"')\";\r\n").getBytes());
                fileOutputStream.write(("}\r\n").getBytes());
                fileOutputStream.write(("tjhUI;\r\n").getBytes());
                fileOutputStream.close();
                //执行.mel文件
                String commandStr = "cmd /c \""+mayaFile+"\"";
                log.info("command: "+commandStr);
                if (this.exeCmd(commandStr)){
                    log.info("userSetup.mel implement success");
                }else {
                    log.info("userSetup.mel implement failed");
                }
            }else{
                //放弃当前渲染场景
                this.updateSteps(progressControl);
            }
        }
    }

    /**
     * 执行.mel文件
     * @param commandStr
     * @return
     */
    public Boolean exeCmd(String commandStr) {
        BufferedReader br = null;
        Boolean flag = false;
        try {
            Process p = Runtime.getRuntime().exec(commandStr);
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            flag = true;
        } catch (Throwable e) {
            log.info("implement:" + e.getMessage());
            flag = false;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    log.info("implement2:" + e.getMessage());
                    flag = false;
                }
            }
        }
        return flag;
    }
    private void updateSteps(ProgressControl progressControl){
        List<ProgressSteps> progressStepsList = progressStepsSerivce.findByGirardId(progressControl);
        ProgressSteps modelStep = progressStepsList.get(0);
        modelStep.setCompletedFiles(0);
        progressStepsSerivce.updateCompletedFiles(modelStep);
    }
}
